<template>
    <el-container class="buy_order_form_container">
        <el-main>
            <el-card class="box-card">
                <div slot="header" class="clearfix" style="padding-left: 0;"
                     v-contraction="{close:dialog, click: contractionClick('buyOrderFormTableRef')}">
                    <el-form ref="buyOrderForm" :rules="rules" :model="formData" label-width="100px"
                             v-enterToNext>
                        <el-row :gutter="15">
                            <el-col :span="8" v-if="onlyOneSupplier">
                                <el-form-item label="供应商" prop="supplier_sid">
                                    <vSelectBottom v-model="formData.supplier_sid" type="supplierDrawer"
                                                   @event="handleSupplierEvent" :options="supplierOptions"
                                                   :disabled="!isEditFlag" />
                                </el-form-item>
                            </el-col>
                            <el-col :span="8">
                                <el-form-item label="采购日期" prop="order_date">
                                    <el-date-picker v-model="formData.order_date" type="date"
                                                    value-format="yyyy-MM-dd"
                                                    :disabled="!isEditFlag" style="width: 100%;" />
                                </el-form-item>
                            </el-col>
                            <el-col :span="8" v-if="type === 'buy'">
                                <el-form-item label="采购单号" prop="code">
                                    <el-input v-model="formData.code" :placeholder="isEditFlag ? '留空则系统自动分配': ''" autocomplete="off" clearable
                                              :disabled="!isEditFlag"></el-input>
                                </el-form-item>
                            </el-col>
                            <el-col :span="8" v-if="onlyOneSupplier">
                                <el-form-item label="供应商联系人" prop="supplier_contract_name">
                                    <el-input v-model="formData.supplier_contract_name" autocomplete="off" clearable
                                              :disabled="!isEditFlag"></el-input>
                                </el-form-item>
                            </el-col>
                            <el-col :span="8" v-if="onlyOneSupplier">
                                <el-form-item label="供应商联系电话" prop="supplier_contract_phone">
                                    <el-input v-model="formData.supplier_contract_phone" autocomplete="off" clearable
                                              :disabled="!isEditFlag"></el-input>
                                </el-form-item>
                            </el-col>
                            <el-col :span="8">
                                <el-form-item label="要求发货时间" prop="req_delivery_date">
                                    <el-date-picker v-model="formData.req_delivery_date" type="date"
                                                    value-format="yyyy-MM-dd"
                                                    :disabled="!isEditFlag" style="width: 100%;" />
                                </el-form-item>
                            </el-col>
                            <el-col :span="8">
                                <el-form-item label="要求到货时间" prop="req_receive_date">
                                    <el-date-picker v-model="formData.req_receive_date" type="date"
                                                    value-format="yyyy-MM-dd"
                                                    :disabled="!isEditFlag" style="width: 100%;" />
                                </el-form-item>
                            </el-col>
                            <el-col :span="8">
                                <el-form-item label="实际到货时间" prop="real_receive_date">
                                    <el-date-picker v-model="formData.real_receive_date" type="date"
                                                    value-format="yyyy-MM-dd"
                                                    :disabled="!isEditFlag" style="width: 100%;" />
                                </el-form-item>
                            </el-col>
                            <el-col :span="8">
                                <el-form-item label="发货方式" prop="delivery_mode">
                                    <el-input v-model="formData.delivery_mode" autocomplete="off" clearable
                                              :disabled="!isEditFlag"></el-input>
                                </el-form-item>
                            </el-col>
                            <el-col :span="8">
                                <el-form-item label="供应商包邮" prop="free_shipping">
                                    <el-checkbox v-model="formData.free_shipping" :true-label="1" :false-label="0"
                                                 :disabled="!isEditFlag" @change="calcShouldPayAmount()" />
                                </el-form-item>
                            </el-col>
                            <el-col :span="8" v-if="type === 'buy'">
                                <el-form-item label="预估运费" prop="pre_freight">
                                    <el-input v-model="formData.pre_freight" autocomplete="off" clearable
                                              :disabled="!isEditFlag"></el-input>
                                </el-form-item>
                            </el-col>
                            <el-col :span="8" v-if="type === 'buy'">
                                <el-form-item label="实付运费" prop="real_freight">
                                    <el-input v-model="formData.real_freight" autocomplete="off" clearable
                                              :disabled="!isEditFlag" @change="calcShouldPayAmount()"></el-input>
                                </el-form-item>
                            </el-col>
                            <el-col :span="8" v-if="type === 'buy'">
                                <el-form-item label="应付金额" prop="should_pay_amount">
                                    <el-input v-model="formData.should_pay_amount" autocomplete="off" clearable
                                              :disabled="!isEditFlag" readonly placeholder="自动计算"></el-input>
                                </el-form-item>
                            </el-col>
                            <el-col :span="8" v-if="type === 'buy' && onlyOneSupplier">
                                <el-form-item label="抹零" prop="ignore_amount">
                                    <el-input v-model="formData.ignore_amount" autocomplete="off" clearable
                                              :disabled="!isEditFlag" v-double-input="{ len: 4, negative: false }"
                                              @change="calcShouldPayAmount()" />
                                </el-form-item>
                            </el-col>
                            <el-col :span="8" v-if="type === 'buy'">
                                <el-form-item label="已付金额" prop="paid_amount">
                                    <el-input v-model="formData.paid_amount" autocomplete="off" clearable
                                              disabled v-double-input="{ len: 4, negative: false }" />
                                </el-form-item>
                            </el-col>
                            <el-col :span="8">
                                <el-form-item label="业务员" prop="buyer_sid">
                                    <remote-select v-model="formData.buyer_sid" :options="personSelectProps"
                                                   style="width: 100%" :disabled="!isEditFlag" />
                                </el-form-item>
                            </el-col>
                            <el-col :span="16">
                                <el-form-item label="备注" prop="note_info">
                                    <el-input v-model="formData.note_info" autocomplete="off" clearable
                                              :disabled="!isEditFlag"></el-input>
                                </el-form-item>
                            </el-col>
                        </el-row>
                    </el-form>
                </div>
                <div class="card_content">
                    <div class="button_area" v-if="!onlyOneSupplier && isEditFlag">
                        <el-button type="success" @click="handleBatchSetSupplier">批量指定供应商</el-button>
                    </div>
                    <vxeTableTemplate ref="buyOrderFormTableRef" :data="dataList" :options.sync="tableOptions"
                                      @event="handleTableEvent" />
                </div>
            </el-card>
        </el-main>
        <el-footer class="card-foot" height="50px" v-if="!dialog">
            <el-button size="medium" @click="back('/jxcBuyOrder')">返回</el-button>
            <el-button type="primary" size="medium" @click="confirm()" v-if="isEditFlag">确定</el-button>
        </el-footer>
    </el-container>
</template>

<script>
import { mapState } from "vuex";
import JxcDialogBase from "@jxc/mixins/JxcDialogBase";
import clothing from "@jxc/utils/clothing";
import '@jxc/components/vxeTable/ProductDownDialog';
import BatchSetSupplierForm from "./BatchSetSupplierForm";

export default {
    extends: JxcDialogBase,
    name: "BuyOrderForm",
    props: {
        type: {
            type: String,
            default: 'buy',
        },
        row: {
            type: Object,
            default: null,
        },
        detail: {
            type: Boolean,
            default: false,
        },
        reGen: {
            type: Boolean,
            default: false,
        },
    },
    data() {
        const _this = this;
        const validator = ({ cellValue, rule, row }) => {
            if (_this.$utils.isNotEmpty(row.goods_sid) && _this.$utils.isEmpty(cellValue)) {
                return new Error(rule.message)
            }
        };
        return {
            rules: {
                code: [
                    { required: true, message: "请输入采购单号", trigger: "blur" },
                    { max: 32, message: "最大 32 位字符，内容过长，请删减", trigger: "blur", },
                ],
                supplier_sid: [
                    { required: true, message: "请选择供应商", trigger: "change" },
                ],
                order_date: [
                    { required: true, message: "请选择采购日期", trigger: "change" },
                ],
            },
            formData: {},
            dataList: [],
            selectionList: [],
            unitList: [],
            tableOptions: {
                ref: "JxcBuyOrderDialogTable",
                container: ".buy_order_form_container",
                keepSource: true,
                editConfig: {
                    trigger: "click",
                    mode: "cell",
                    showStatus: true,
                },
                editRules: {
                    supplier_sid: [
                        {required: true, validator, message: '请选择'},
                    ],
                    goods_name: [
                        {required: true, validator, message: '请选择'},
                    ],
                    price: [
                        {required: true, validator, message: '请输入'},
                    ],
                    qty: [
                        {required: true, validator, message: '请输入'},
                    ],
                    unit_name: [
                        {required: true, validator, message: '请选择'},
                    ],
                },
                showSummary: true,
                summaryArray: [ 'qty', 'amount', 'tax_amount', 'total_amount' ],
                columns: [],
                baseColumns: [
                    {
                        label: "供应商",
                        prop: "supplier_sid",
                        align: "center",
                        editRender: {
                            name: "vSelectBottom",
                            props: {
                                type: 'supplierDrawer',
                                options: {
                                    disabled: true,
                                    placeholder: '请选择供应商',
                                },
                            },
                            events: {
                                event({ row }, { data }) {
                                    _this.$set(row, 'supplier_sid', data ? data.sid : '');
                                    _this.$set(row, 'supplier_display', data ? data.display : '');
                                },
                            },
                        },
                        formatter(row) {
                            return row.supplier_display || '';
                        },
                    },
                    {
                        label: "物料",
                        prop: "goods_name",
                        align: "center",
                        editRender: {
                            name: "vProductDownDialog",
                            type: 'buy',
                            events: { event: _this.handleGoodsEvent },
                        },
                    },
                    {
                        label: "规格",
                        prop: "spec_info",
                        align: "center",
                    },
                    {
                        label: "数量",
                        prop: "qty",
                        align: "center",
                        width: 90,
                        editRender: {
                            name: "CustomInput",
                            autoselect: true,
                            props: {
                                doubleInput: {
                                    len: 3,
                                    negative: false,
                                },
                            },
                            events: {
                                input: _this.rewriteChangeRow,
                            },
                            filter(row) {
                                return _this.$utils.isNotEmpty(row.goods_sid);
                            },
                        },
                    },
                    {
                        label: "单位",
                        prop: "unit_name",
                        align: "center",
                        width: 90,
                        editRender: {
                            name: "CustomSelect",
                            autoselect: true,
                            props: {
                                filterable: true,
                                clearable: true,
                                dataMethod(row) {
                                    return (row.price_list || []).map(item => {
                                        return {
                                            label: item.unit_name,
                                            value: item.unit_name,
                                        };
                                    });
                                },
                            },
                            events: {
                                change: _this.rewriteChangeRow,
                            },
                        },
                    },
                    {
                        label: "原价",
                        prop: "list_price",
                        align: "center",
                        width: 90,
                        editRender: {
                            name: "CustomInput",
                            autoselect: true,
                            props: {
                                doubleInput: {
                                    len: 4,
                                    negative: false,
                                },
                            },
                            events: {
                                input: _this.rewriteChangeRow,
                            },
                            filter(row) {
                                return _this.$utils.isNotEmpty(row.goods_sid);
                            },
                        },
                        formatter: (row, column, scope) => _this.formatterAmount(row, column, scope, 4),
                    },
                    {
                        label: "折扣",
                        prop: "price_rate",
                        align: "center",
                        width: 90,
                        editRender: {
                            name: "CustomInput",
                            autoselect: true,
                            props: {
                                doubleInput: {
                                    len: 4,
                                    negative: false,
                                },
                            },
                            events: {
                                input: _this.rewriteChangeRow,
                            },
                            filter(row) {
                                return _this.$utils.isNotEmpty(row.goods_sid);
                            },
                        },
                        formatter(row) {
                            let price_rate = _this.$utils.isEmpty(row.price_rate) ? 0 : row.price_rate;
                            price_rate = _this.$utils.accMul(price_rate, 100);
                            return `${ Number(Number(price_rate).toFixed(2)) } %`;
                        },
                    },
                    {
                        label: "不含税单价",
                        prop: "price",
                        align: "center",
                        width: 110,
                        editRender: {
                            name: "CustomInput",
                            autoselect: true,
                            props: {
                                doubleInput: {
                                    len: 4,
                                    negative: false,
                                },
                            },
                            events: {
                                input: _this.rewriteChangeRow,
                            },
                            filter(row) {
                                return _this.$utils.isNotEmpty(row.goods_sid);
                            },
                        },
                        formatter: (row, column, scope) => _this.formatterAmount(row, column, scope, 4),
                    },
                    {
                        label: "不含税金额",
                        prop: "amount",
                        align: "center",
                        width: 90,
                        formatter: (row, column, scope) => _this.formatterAmount(row, column, scope, 2),
                    },
                    {
                        label: "税率",
                        prop: "tax_rate",
                        align: "center",
                        width: 80,
                        editRender: {
                            name: "CustomInput",
                            autoselect: true,
                            props: {
                                doubleInput: {
                                    len: 4,
                                    negative: false,
                                },
                            },
                            events: {
                                input: _this.rewriteChangeRow,
                            },
                            filter(row) {
                                return _this.$utils.isNotEmpty(row.goods_sid);
                            },
                        },
                        formatter(row) {
                            let price_rate = _this.$utils.isEmpty(row.tax_rate) ? 0 : row.tax_rate;
                            price_rate = _this.$utils.accMul(price_rate, 100);
                            return `${ Number(Number(price_rate).toFixed(2)) }%`;
                        },
                    },
                    {
                        label: "税额",
                        prop: "tax_amount",
                        align: "center",
                        width: 90,
                        formatter: (row, column, scope) => _this.formatterAmount(row, column, scope, 2),
                    },
                    {
                        label: "含税金额",
                        prop: "total_amount",
                        align: "center",
                        width: 90,
                        formatter: (row, column, scope) => _this.formatterAmount(row, column, scope, 2),
                    },
                    {
                        label: "备注",
                        prop: "note_info",
                        align: "center",
                        editRender: {
                            name: 'CustomInput',
                            filter(row) {
                                return _this.$utils.isNotEmpty(row.goods_sid);
                            },
                        },
                    },
                    {
                        label: "基本数量",
                        prop: "qty4base",
                        align: "center",
                        width: 100,
                    },
                    {
                        label: "销售基本数量",
                        prop: "sale_req_qty4base",
                        align: "center",
                        width: 100,
                    },
                    {
                        label: "当前库存",
                        prop: "stock_qty",
                        align: "center",
                        width: 80,
                    },
                    {
                        label: "采购订单",
                        prop: "gen_bill_num",
                        align: "center",
                        width: 100,
                        formatter(row) {
                            let gen_bill_num = _this.$utils.isEmpty(row.gen_bill_num) ? 0 : row.gen_bill_num;
                            return gen_bill_num > 0 ? `订单数量：${gen_bill_num} 采购数量：${ row.gen_buy_qty4base }${ row.gen_buy_qty4base }` : '未生成';
                        },
                    },
                ],
                operates: {
                    fixed: "right",
                    list: [
                        {
                            id: 'add1',
                            size: 'mini',
                            show: true,
                            tooltip: {
                                content: '插入',
                            },
	                        svg: {
		                        iconClass: 'icon-insert',
	                        },
                            filter: (row) => {
                                return _this.isEditFlag;
                            },
                            method: (index, row) => {
                                _this.handleAddRow(row, -1);
                            }
                        },
                        {
                            id: 'add2',
                            size: 'mini',
                            show: true,
                            tooltip: {
                                content: '追加',
                            },
	                        svg: {
		                        iconClass: 'icon-append',
	                        },
                            filter: (row) => {
                                return _this.isEditFlag;
                            },
                            method: (index, row) => {
                                _this.handleAddRow(row, 1);
                            }
                        },
                        {
                            id: 'del',
                            icon: 'fa fa-trash-o',
                            size: 'mini',
                            type: 'danger',
                            show: true,
                            tooltip: {
                                content: '删除',
                            },
                            filter: (row) => {
                                return _this.isEditFlag;
                            },
                            method: (index, row) => {
                                let dataList = _this.dataList.map(item => $.extend({}, item));
                                dataList = dataList.filter(item => item._index !== row._index);
                                _this.dataList = _this.resetIndex(dataList);
                                if (!_this.$utils.isNotEmptyList(dataList)) {
                                    _this.handleAddRow(null, 1);
                                }
                            }
                        }
                    ],
                },
                pagination: false,
                subHeight: -15,
            },
            bizOfficeList: [],
            bizOfficeContractList: [],
        };
    },
    computed: {
        ...mapState(['userInfo']),
        ...mapState('jxc', ['setting']),
        isEditFlag() {
            if (this.detail) {
                return false;
            }
            if (this.reGen) {
                return true;
            }
            return this.$utils.isEmpty(this.formData.audit_state) || this.formData.audit_state === 0;
        },
        onlyOneSupplier() {
            if (this.type === 'sale2buy') {
                return false;
            }
            return this.setting.buy_order_only_one_supplier === 1;
        },
        formTableRef() {
            return this[this.tableOptions.ref];
        },
    },
    watch: {
        row: {
            handler() {
                this.init();
            },
            deep: true,
            immediate: true,
        },
        dataList: {
            handler() {
                this.calcShouldPayAmount();
            },
            deep: true,
        },
    },
    methods: {
        async init() {
            const _this = this;
            if (!_this.row) {
                return;
            }
            if (_this.detail) {
                _this.rules = {};
            }
            await _this.storeDispatch('jxc/initSetting');
            _this.initTableOptions();
            if (_this.$refs.buyOrderForm) {
                _this.$refs.buyOrderForm.clearValidate();
            }
            if (_this.type === 'sale2buy') {
                _this.initData4Sale2Buy();
                return;
            }
            if (_this.$utils.isNotEmpty(_this.row.sid)) {
                await _this.initData(_this.row.sid);
            } else {
                const initData = {};
                if (_this.$utils.isNotEmpty(_this.userInfo.group_person_sid)) {
                    initData.buyer_sid = _this.userInfo.group_person_sid;
                }
                _this.formData = $.extend({}, initData, {
                    order_date: _this.$XEUtils.toDateString(new Date(), 'yyyy-MM-dd'),
                });
                _this.generateCode();
            }
            if (!_this.$utils.isNotEmptyList(_this.dataList)) {
                for (let i = 0; i < 5; i++) {
                    _this.handleAddRow(null, 1);
                }
            }
        },
        initTableOptions() {
            const _this = this;
            let columns = _this.tableOptions.baseColumns.map(item => $.extend({}, item));
            columns = clothing.resetTableColumns(_this.setting, columns);
            let operates = $.extend({}, _this.tableOptions.operates);
            if (!_this.isEditFlag) {
                columns = columns.map(item => {
                    let obj = $.extend({}, item);
                    delete obj.editRender;
                    return obj;
                });
                columns.push({
                    label: "退货数量",
                    prop: "return_qty",
                    align: "center",
                    width: 100,
                });
                columns.push({
                    label: "退货金额",
                    prop: "return_amount",
                    align: "center",
                    formatter: (row, column, scope) => this.formatterAmount(row, column, scope, 2),
                    width: 100,
                });
                operates = {};
            }
            if (_this.onlyOneSupplier) {
                columns = columns.filter(item => item.prop !== 'supplier_sid');
            }
            if (_this.type === 'buy') {
                columns = columns.filter(item => ['qty4base', 'sale_req_qty4base', 'stock_qty', 'gen_bill_num'].indexOf(item.prop) === -1);
            }
            _this.tableOptions = $.extend({}, _this.tableOptions, {
                columns, operates,
                multiSelect: !_this.onlyOneSupplier && _this.isEditFlag,
                getMaxHeight: !_this.dialog ? undefined : () => {
                    const height = $(_this.getActiveTabsContainer()).height();
                    return height * 0.8 - 250 - (!_this.onlyOneSupplier && _this.isEditFlag ? 50 : 0);
                },
            });
        },
        initData(sid) {
            const _this = this;
            return _this.fetchData(_this.$api.API_GetJxcBuyOrderBySid, {
                sid,
            }).then(result => {
                let resData = result.data || {};
                let dataList = clothing.transferDetailList(_this.setting, resData.detail_list, _this.tableOptions.columns);
                resData.paid_amount = _this.reGen ? 0 : resData.paid_amount;
                if (_this.reGen) {
                    resData.gen_finance=0;
                    resData.in_bill= 0;
                    resData.in_bill_sid=null;
                    resData.update_date=null;
                    resData.updator_sid=null;
                    resData.updator_name=null;
                    resData.audit_state=0;
                    resData.audit_date=null;
                    resData.auditor_sid=null;
                    resData.auditor_name=null;
                    resData.return_qty=null;
                    resData.return_amount=null;
                    resData.ignore_amount=null;
                    resData.invoice_state=0;
                    resData.review_date=null;
                    resData.review_person_sid=null;
                    resData.order_date = new Date();
                }
                _this.formData = resData;
                _this.dataList = _this.resetIndex(dataList);
                if (_this.reGen) {
                    _this.generateCode();
                } else {
                    _this.oldCode = resData.code;
                }
            }).catch(() => {
            });
        },
        initData4Sale2Buy() {
            const _this = this;
            return _this.fetchData(_this.$api.API_GetJxcSale2BuyData, {
                sale_order_list: _this.row.sale_order_list || [],
                sale_order_detail_list: _this.row.sale_order_detail_list || [],
            }).then(result => {
                let resData = result.data || {};
                let dataList = clothing.transferDetailList(_this.setting, resData.detail_list, _this.tableOptions.columns);
                _this.formData = resData;
                _this.dataList = _this.resetIndex(dataList)
            }).catch(() => {
            });
        },
        generateCode() {
            const _this = this;
            if (_this.$utils.isNotEmpty(_this.oldCode) && _this.oldCode === _this.formData.code) {
                return;
            }
            return _this.storeDispatch('base/getAutoOrderCode', {
                rule_code: 'jxc_buy_order',
            }).then(data => {
                _this.formData = $.extend({}, _this.formData, {
                    code: data,
                });
                _this.oldCode = data;
                if (_this.$refs.buyOrderForm) {
                    _this.$refs.buyOrderForm.clearValidate('code');
                }
            });
        },
        rewriteChangeRow({ row, column }) {
            const _this = this;
            column = Object.assign({}, column, column.params)
            // 手动限制控制数字位数
            if (column.editRender && column.editRender.double) {
                _this.$set(row, column.prop, _this.$XEUtils.DoubleInput(row[column.prop], column.editRender.double));
            }
            if (column.editRender && column.editRender.integer) {
                _this.$set(row, column.prop, _this.$XEUtils.IntInput(row[column.prop]));
            }
            if (column.prop === 'unit_name') {
                const goodsPrice = (row.price_list || []).find(item => item.unit_name === row[column.prop]);
                if (goodsPrice) {
                    _this.$set(row, "price", goodsPrice.buy_price);
                    _this.$set(row, "unit_qty", goodsPrice.qty);
                    if (_this.$utils.isNotEmpty(row.price_rate)) {
                        _this.$set(row, "list_price", _this.$utils.accDiv2Fixed(row.price, row.price_rate, 4));
                    }
                }
                _this.calcAmount(row);
                return;
            }
            if (column.prop === 'qty') {
                _this.calcAmount(row);
                return;
            }
            if (column.prop === 'price') {
                _this.calcAmount(row);
                if (_this.$utils.isNotEmpty(row.list_price) && Number(row.list_price) > 0) {
                    _this.$set(row, "price_rate", Number(_this.$utils.accDiv2Fixed(row.price, row.list_price, 4)));
                }
                return;
            }
            if (column.prop === 'list_price') {
                if (_this.$utils.isNotEmpty(row.price_rate)) {
                    _this.$set(row, "price", _this.$utils.accMul(row.list_price, row.price_rate));
                }
                _this.calcAmount(row);
                return;
            }
            if (column.prop === 'price_rate') {
                if (_this.$utils.isEmpty(row.price_rate)) {
                    _this.$set(row, "price_rate", 0);
                }
                if (_this.$utils.isNotEmpty(row.list_price)) {
                    _this.$set(row, "price", _this.$utils.accMul(row.list_price, row.price_rate));
                }
                _this.calcAmount(row);
                return;
            }
            if (column.prop === 'tax_rate') {
                if (_this.$utils.isEmpty(row.tax_rate)) {
                    _this.$set(row, "tax_rate", 0);
                }
                _this.calcTaxAmount(row)
            }
        },
        calcAmount(row) {
            const _this = this;
            if (_this.$utils.isNotEmpty(row.qty) && _this.$utils.isNotEmpty(row.unit_qty)) {
                _this.$set(row, "qty4base", _this.$utils.accMul2Fixed(row.qty, row.unit_qty, 3));
            }
            if (_this.$utils.isNotEmpty(row.qty) && _this.$utils.isNotEmpty(row.price)) {
                let amount = _this.$utils.accMul(row.qty, row.price);
                _this.$set(row, "amount", amount);
                _this.calcTaxAmount(row)
            }
        },
        calcTaxAmount(row) {
            const _this = this;
            if (_this.$utils.isNotEmpty(row.tax_rate) && _this.$utils.isNotEmpty(row.amount)) {
                // let addRate = _this.$utils.accAdd(1, row.tax_rate);
                // let amount = _this.$utils.accDiv2Fixed(row.amount, addRate, 4);
                // amount = _this.$utils.accMul2Fixed(amount, row.tax_rate, 2);
                // _this.$set(row, "tax_amount", amount);
                _this.$set(row, "tax_amount", _this.$utils.accMul2Fixed(row.amount, row.tax_rate, 2));
                _this.$set(row, "total_amount", _this.$utils.accAdd(row.amount, row.tax_amount));
            }
        },
        handleAddRow(row, state = 1) {
            const _this = this;
            let dataList = _this.dataList.map(item => $.extend({}, item));
            let addData = clothing.genInitData(_this.setting, {
                list_price: null,
                price_rate: 1,
                price: null,
                qty: null,
                note_info: null,
                tax_rate: _this.setting.default_tax_ratio || 0,
            });
            if (row && state <= 0) {
                let index = _this.dataList.findIndex(item => item._index === row._index);
                if (index !== -1) {
                    if (index === 0) {
                        dataList.unshift(addData);
                    } else {
                        dataList.splice(index, 0, addData);
                    }
                } else {
                    dataList.push(addData);
                }
            } else {
                dataList.push(addData);
            }
            _this.dataList = _this.resetIndex(dataList);
        },
        handleSupplierEvent(event) {
            const _this = this;
            if (!_this.isEditFlag) {
                return;
            }
            if (typeof event.value !== 'undefined') {
                _this.formData = $.extend({}, _this.formData, {
                    delivery_mode: event.data ? event.data.delivery_mode : '',
                    supplier_sid: event.value,
                    supplier_name: event.data ? event.data.name : '',
                    supplier_contract_name: event.data ? event.data.linker_name : '',
                    supplier_contract_phone: event.data ? event.data.linker_mobile : '',
                });
                if (_this.$utils.isNotEmpty(event.value)) {
                    if (_this.isEditFlag) {
                        _this.generateCode();
                    }
                    return;
                }
            }
            if (_this.isEditFlag) {
                return;
            }
            _this.formData = $.extend({}, _this.formData, {
                supplier_sid: '',
                supplier_name: '',
                supplier_contract_name: '',
                supplier_contract_phone: '',
            });
        },
        handleGoodsEvent(e, param) {
            const _this = this;
            let { row, column, params } = param;
            if (params.row) {
                _this.$set(row, 'goods_sid', params.row.sid);
                _this.$set(row, column.property, params.row.name);
                _this.$set(row, 'spec_info', params.row.spec);
                const priceList = (params.row.price_list || []).map(item => $.extend({}, item));
                _this.$set(row, 'price_list', priceList);
                const defaultPrice = priceList.find(item => item.default_for_bill_list.includes('j'));
                if (defaultPrice) {
                    _this.$set(row, 'unit_name', defaultPrice.unit_name);
                    _this.$set(row, 'price', defaultPrice.buy_price);
                    _this.$set(row, 'list_price', defaultPrice.buy_price);
                } else {
                    _this.$set(row, 'unit_name', params.row.base_unit);
                    _this.$set(row, 'price', params.row.base_buy_price);
                    _this.$set(row, 'list_price', params.row.base_buy_price);
                }
                if (clothing.isClothing(_this.setting)) {
                    _this.$set(row, 'spec_preset_value', params.row.spec_preset_value);
                    _this.$set(row, 'preset_product_map', params.row.clothing_preset_product_map);
                    _this.$set(row, 'clothing_color_name', params.row.clothing_color_name);
                }
                _this.calcAmount(row);
                _this.calcTaxAmount(row);
            }
        },
        calcShouldPayAmount() {
            const _this = this;
            let totalAmount = 0;
            if (_this.$utils.isEmpty(_this.formData.free_shipping) || _this.formData.free_shipping === 0) {
                if (_this.$utils.isNotEmpty(_this.formData.real_freight) && !isNaN(Number(_this.formData.real_freight))) {
                    totalAmount = _this.$utils.accAdd(totalAmount, Number(_this.formData.real_freight));
                }
            }
            let filter = _this.dataList.filter(item => _this.$utils.isNotEmpty(item.total_amount));
            if (_this.$utils.isNotEmptyList(filter)) {
                filter.forEach(item => {
                    totalAmount = _this.$utils.accAdd(totalAmount, item.total_amount);
                });
            }
            if (_this.$utils.isNotEmpty(_this.formData.ignore_amount) && !isNaN(Number(_this.formData.ignore_amount))) {
                totalAmount = _this.$utils.accSubtr(totalAmount, Number(_this.formData.ignore_amount));
            }
            if (Number(totalAmount) < 0) {
                totalAmount = 0;
            }
            _this.formData = $.extend({}, _this.formData, {
                should_pay_amount: totalAmount,
            });
        },
        handleTableEvent(event) {
            if (event.type === 'selectionChange') {
                this.selectionList = event.value;
            }
        },
        handleBatchSetSupplier() {
            const _this = this;
            if (!_this.checkSelection(_this.selectionList, true)) {
                return;
            }
            _this.$dialog({
                title: '批量指定供应商',
                width: '400px',
                component: {
                    value: BatchSetSupplierForm,
                    event(e) {
                        if (e.type === 'confirm'){
                            let selectedList = _this.selectionList.map(item => item._index);
                            _this.dataList.forEach(item => {
                                if (selectedList.indexOf(item._index) !== -1) {
                                    _this.$set(item, 'supplier_sid', e.value.supplier_sid);
                                    _this.$set(item, 'supplier_display', e.value.supplier_display);
                                }
                            });
                        }
                    },
                },
            });
        },
        async confirm() {
            const _this = this;
            let valid = await _this.validateForm('buyOrderForm');
            if (!valid) {
                return false;
            }
            if (_this.formTableRef) {
                const errMap = await _this.formTableRef.validate(true);
                if (errMap) {
                    return false;
                }
            }
            let dataList = _this.dataList.filter(item => _this.$utils.isNotEmpty(item.goods_sid));
            if (!_this.$utils.isNotEmptyList(dataList)) {
                _this.$message.error('订单明细不能为空');
                return false;
            }
            if (!_this.onlyOneSupplier) {
                let filter = dataList.filter(item => _this.$utils.isEmpty(item.supplier_sid));
                if (_this.$utils.isNotEmptyList(filter)) {
                    _this.$message.error(`序号：${ filter[0]._index + 1 } 供应商不能为空`);
                    return false;
                }
            }
            dataList = clothing.procSubData(_this.setting, dataList);
            let subData = $.extend({}, _this.formData);
            subData.detail_list = dataList.map(item => {
                let obj = $.extend({}, item);
                obj.sn = item._index + 1;
                if (_this.onlyOneSupplier && _this.$utils.isNotEmpty(_this.formData.supplier_sid)) {
                    obj.supplier_sid = _this.formData.supplier_sid;
                }
                delete obj.amount;
                if (_this.reGen) {
                    delete obj.id;
                    delete obj.sid;
                    delete obj.order_sid;
                }
                return obj;
            });
            let amountFieldList = ['pre_freight', 'real_freight', 'ignore_amount', 'paid_amount'];
            amountFieldList.forEach(field => {
                if (_this.$utils.isNotEmpty(subData[field])) {
                    let value = Number(subData[field]);
                    subData[field] = isNaN(value) ? '' : value;
                }
            });
            let url = _this.$api.API_SaveJxcBuyOrder;
            if (_this.type === 'sale2buy') {
                url = _this.$api.API_SaveJxcBuyOrder4Sale2Buy;
            }
            if (_this.reGen) {
                delete subData.id;
                delete subData.sid;
                delete subData.buyer_sid;
            }
            delete subData.invoice_type;
            if (!_this.onlyOneSupplier) {
                subData.ignore_amount = 0;
            }
            return _this.fetchData(url, subData).then(() => {
                if (_this.type === 'sale2buy') {
                    _this.$message.success('生成采购单成功！');
                } else {
                    _this.$message.success('保存成功！');
                }
                if (!_this.dialog) {
                    _this.back('/jxcBuyOrder', 'refreshJxcBuyOrder');
                }
                return true;
            }).catch(() => {
                return false;
            });
        },
    },
}
</script>

<style lang="less" rel="stylesheet/less" scoped>
.buy_order_form_container {
    width: 100%;
    height: 100%;

    /deep/.el-checkbox {
        line-height: 1;
    }

    /deep/.card_content {
        position: relative;

        .button_area {
            position: absolute;
            top: -30px;
            left: 0;
        }
    }

    .card-foot {
        gap: 120px;
        justify-content: center;

        .el-button {
            width: 120px;
        }
    }
}
</style>
